package cn.xdj.blue.java.netty5.simple.server;

import java.net.InetAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class MyNettyServer implements Runnable {

	private int port;

	public MyNettyServer(int port) {
		this.port = port;
	}

	public void run() {
		System.out.println("---监听启动---");
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup work = new NioEventLoopGroup();
		ServerBootstrap server = new ServerBootstrap();
		server.group(boss, work)
			.channel(NioServerSocketChannel.class)
			.option(ChannelOption.SO_BACKLOG, 1024)
			.childHandler(new ChannelInitializer<SocketChannel>() {
				protected void initChannel(SocketChannel arg) throws Exception {
					System.out.println("---一个请求---");
					
					System.out.println("报告");
					System.out.println("信息：有一客户端链接到本服务端");
					System.out.println("IP:"+InetAddress.getLocalHost().getHostAddress());
					System.out.println("Port:"+InetAddress.getLocalHost().getHostName());
					System.out.println("报告完毕");
					/*arg.pipeline().addLast(new LineBasedFrameDecoder(1024));
					arg.pipeline().addLast(new StringDecoder());*/
					arg.pipeline().addLast(new HelloServerHandler());
					System.out.println("--ChannelInitializer--");
				}
			} );
		try {
			ChannelFuture channelFuture = server.bind(port).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		finally{
			boss.shutdownGracefully();
			work.shutdownGracefully();
		}

	}

}
